package com.prj.ufdm.cloud.client.action;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.prj.ufdm.cloud.client.enums.ServiceNameConsts;

@RestController
@Configurable
public class EurekaClientService {

	@Autowired
	RestTemplate restTemplate;
	
	@Autowired
	LoadBalancerClient loadBalancerClient;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/ms/test")
	@ResponseBody
	public Map<String,Object>  routeMsTest() {
		
		System.out.println("\n 通过 restTemplate 执行... \n");
		
		String url = "http://"+ServiceNameConsts.SERVICE_MS_TEST+"/api/test/first/demo";
		
		Map<String,Object> resultMap = restTemplate.getForObject(url, Map.class);
		
		System.out.println("\n resultMap:"+resultMap);
		
		return resultMap;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/ms/news")
	@ResponseBody
	public Map<String,Object>  routeMsNews() {
		
		System.out.println("\n 通过 restTemplate 执行... \n");
		
		String url = "http://"+ServiceNameConsts.SERVICE_MS_NEWS+"/api/news/first/demo";
		
		Map<String,Object> resultMap = restTemplate.getForObject(url, Map.class);
		
		System.out.println("\n resultMap:"+resultMap);
		
		return resultMap;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/lt")
	@ResponseBody
	public Map<String,Object>  loadBalancerClientTest() {
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		// 查看当前使用到的主机
		ServiceInstance serviceInstance = this.loadBalancerClient.choose(ServiceNameConsts.SERVICE_MS_TEST);
		String balanceHost =serviceInstance.getHost()+":"+serviceInstance.getPort();
		System.out.println("\n balanceHost:"+balanceHost);

		// 这里调用相当于再调用一次 loadBalancerClient.choose(ServiceNameConsts.SERVICE_MS_TEST) 方法
		String url = "http://"+ServiceNameConsts.SERVICE_MS_TEST+"/api/test/first/demo";
		resultMap = restTemplate.getForObject(url, Map.class);
		System.out.println("\n resultMap:"+resultMap);
		
		return resultMap;
	}
}
